<template>
	<view class="activityDetail-index">
		<view class="header p-3">
			<view class="header_img mb-2">
				<image v-if="itemData.responsibleimg" :src="showImage(itemData.responsibleimg[0].storageKey)"
					mode="scaleToFill" class="img"></image>
			</view>
			<view class="header_title font-weight-bold">{{itemData.activityName}}</view>
			<view class="header_mintitle mt-2  flex">
				<view class="p-1 ">招募人数 {{itemData.participateCount}}/{{itemData.numberRecruits}}</view>
				<view class="p-1  ml-3">活动时长 {{itemData.activityDuration}}小时</view>
			</view>

			<view class="header_time mt-3 flex align-center">
				<image src="../../static/icon/garter.png" mode="aspectFill"></image>
				<span class="ml-1" v-if="itemData.beginTime">集合时间：{{dayjs(itemData.gatherTime).format("MM/DD HH:mm")}}
				</span>

			</view>

			<view class="header_time mt-2 flex align-center">
				<image src="../../static/icon/start-end.png" mode="aspectFill"></image>
				<span class="ml-1" v-if="itemData.beginTime">开始~结束时间：{{dayjs(itemData.beginTime).format("MM/DD HH:mm")}}
					~
				</span>
				<span class="ml-1" v-if="itemData.endTime">{{dayjs(itemData.endTime).format("MM/DD HH:mm")}}</span>
			</view>


			<view class="header_time mt-2">
				<image src="../../static/icon/address.png" mode="aspectFill"></image>
				{{itemData.serviceAddressAddress || '--'}}
			</view>
			<view class="header_type mt-3 ">
				<view class="item">
					<view class="title mb-1">活动类型</view>
					<view class="text">{{itemData.activityType || '--'}}</view>
				</view>
				<!-- <view class="item">
					<view class="title mb-1">服务对象</view>
					<view class="text">{{itemData.servicePeople || '--'}}</view>
				</view> -->
				<view class="item">
					<view class="title mb-1">集合地点</view>
					<view class="text">{{itemData.activityPlace || '--'}}</view>
				</view>
			</view>

			<view class="header_info mt-3 ">
				<view class="left_img">
					<image v-if="organizationData.logo" :src="showImage(organizationData?.logo[0]?.storageKey)" mode=""
						class="img"></image>
				</view>
				<view class="right_person ml-3 mb-2">
					<view class="team_name font-weight-bold">{{organizationData.organizationName}}</view>
					<view class="info flex align-center pt-1" v-for="item in contactPerson">
						<uni-icons type="contact-filled" size="14" color="#fff"></uni-icons>
						<span class="ml-1 ">联络人{{item.name}} {{item.mobile || '-'}}</span>
					</view>

				</view>
			</view>
		</view>
		<view class="volunteerList mt-3 p-3">
			<view>报名志愿者列表 <text class="num" v-if="organizationNum">已报名 ( <text
						class="organizationNum">{{organizationNum}}</text> )人</text></view>
			<view class="person-box mt-3">
				<view class="item flex flex-column align-center" v-for="(item,index) in showOrgData">
					<view class="item_img flex mt-1 justify-center align-center"
						:style="{'backgroundColor':addBgColorList[index]}">
						<view class="name">{{item.nameName.slice(0,1)}}</view>

					</view>
					<view class="name mt-1">{{item.nameName}}</view>
					<view v-if="item.title">({{item.title }})</view>
				</view>

			</view>
			<LoadingMore :viewMorestatus="viewMorestatus" :viewNum='viewNum' @viewMore="viewMore"></LoadingMore>

		</view>

		<view class="activeRequirement  mt-3 p-3 " v-if="itemData.activityRequire">
			<view class="font-md font-weight-bold">活动要求</view>
			<view class="tag mt-3 flex flex-wrap align-center">
				<view class="content mb-1" v-for="item in itemData.activityRequire" :key="item">
					<span class="circle border-circle mr-1"></span>{{item.text}}
				</view>


			</view>
		</view>

		<view class="Guarantee  mt-3 p-3" v-if="itemData.activitySupport?.length>0">
			<view class="font-md font-weight-bold">活动保障</view>
			<view class="tag mt-3 flex flex-wrap">
				<uni-tag v-for="(item,index) in itemData.activitySupport" :key="item" circle :text="item.text"
					type="primary" :style="{'marginRight': '16rpx','border': 'none','padding':'12rpx 16rpx'}" />
			</view>

		</view>
		<view class="detail mt-3 p-3">
			<view class="font-md font-weight-bold">活动详情</view>
			<view class="info activityDetail mt-2">

			</view>
		</view>
		<view class="warning p-3">
			<view class="text-default">温馨提示</view>
			<view class="title text-shallow mt-1">
				{{activityDetailData.activityPrompt}}
			</view>
		</view>
		<view class="Application">
			<view v-if="isCanActivity" class="btn" @click="dialogToggle('success')">
				<view class="font-weight-bold">{{isAlreadyActivity ?'我已报名':'我要报名'}}</view>
				<view style="font-size: 28rpx;">(距离活动开始还剩{{deadline}})</view>
			</view>
			<view class="expire-btn btn" v-else style="font-size: 28rpx;">报名时间已过期</view>
		</view>
		<view class="btn">
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确定" title="提示" content="确定进行报名操作?"
					@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import dayjs from 'dayjs';
	import {
		showImage
	} from '../../api/common.js'
	import request from '../../api/index.js'
	import {
		getDictData,
		formatterDictData,
	} from '../../common/common.js'
	import LoadingMore from '../../component/LoadingMore/LoadingMore.vue';


	const itemData = ref({})
	const organizationData = ref({})
	const organizationNum = ref(0)
	const contactPerson = ref([])
	const addBgColorList = ref([])
	const activityDetailData = ref([])
	const deadline = ref('')
	const isCanActivity = ref('')
	const isAlreadyActivity = ref('')
	const userName = ref({})

	const viewMorestatus = ref('more')
	const viewNum = ref(10)
	const showOrgData = ref([])

	
	

	const msgType = ref('')
	const alertDialog = ref('')
	const dialogToggle = (type) => {
		msgType.value = type
		if (isAlreadyActivity.value) {
			uni.showToast({
				title: '我已报名,请注意活动开始时间！',
				icon: 'success'
			})
		} else {
			alertDialog.value.open()
		}

	}
	
	const viewMore = () => {
		console.log("查看更多")
		viewMorestatus.value = 'loading'
		
		
		let length = activityDetailData.value?.formId?.length;
		
		if ((length - viewNum.value) < 10) {
			console.log("===============================================================")
			viewNum.value = length
		
		} else {
			viewNum.value += 10;
		
		
		}
		console.log("length-------", length)
		console.log("viewNum.value-------", viewNum.value)
		setTimeout(() => {
			if (length >= viewNum.value) {
				getActivityDetail()
				viewMorestatus.value = 'more'
			}
		
			if (length == viewNum.value) {
				viewMorestatus.value = 'noMore'
			}
		}, 1000)
	}






	const getActivityDetail = (status) => {
		request({
			url: `/api/volunteer/activity/${itemData.value.id}`,
			method: 'GET',
		}, e => {
			if (e.success) {
				console.log('e-------------', e.data.formId)
				activityDetailData.value = e.data


				activityDetailData.value?.formId.forEach((item) => {

					item.title = formatterDictData('DIC025', item.title)
					if (item.nameName == userName.value) {
						isAlreadyActivity.value = true
					}
					console.log("item.title--------", item.title);
				})

				
				organizationNum.value = activityDetailData.value?.formId.length
				if (organizationNum.value < 10) {
					viewMorestatus.value = 'noMore'
				}


				addBgColor(organizationNum.value)




				// 排序
				activityDetailData.value?.formId.sort((a, b) => {
					// 如果 a 有 title 而 b 没有，则 a 应该在 b 前面
					if (a.title && !b.title) return -1;
					// 如果 b 有 title 而 a 没有，则 b 应该在 a 前面
					if (!a.title && b.title) return 1;
					// 如果两者都有或者都没有 title，则保持原顺序
					return 0;
				});
				let showData = activityDetailData.value?.formId?.slice(0, viewNum.value);
				// let showData = activityDetailData.value?.formId
				console.log("showData----------", showData)
				console.log("activityDetailData.value?.formId----------", activityDetailData.value?.formId)
				showOrgData.value = showData

				if (status == 'init') {
					let doc = ''



					// 获取目标 DOM 元素
					const container = document.getElementsByClassName('activityDetail')[0];

					// 解析 HTML 字符串
					const parser = new DOMParser();
					doc = parser.parseFromString(activityDetailData.value.activityDetails, 'text/html');
					activityDetailData.value.activityDetails = doc.body

					// 将解析后的 DOM 节点插入到目标 DOM 元素
					if (!doc.body.textContent) {
						doc.body = '暂无数据'

					}

					container.appendChild(doc.body);

				}






			} else {

			}
		})
	}
	const dialogConfirm = () => {
		console.log('点击确认-------', itemData.value.id)
		uni.showLoading({
			title: '报名中',
			mask: true
		});
		request({
			url: `/api/volunteer/activity-bd/activity-bd-add`,
			method: 'POST',
			data: {

				activityId: itemData.value.id

			}
		}, e => {

			if (e.success) {
				console.log('e-------------', e.data)
				uni.showToast({
					title: '报名成功',
					icon: 'success'
				})
				getActivityDetail()


			} else {
				uni.showToast({
					title: e.errorMessage,
					icon: 'error'
				})
			}
			uni.hideLoading()
		})


	}


	onLoad((options) => {
		itemData.value = JSON.parse(options.data)

		itemData.value.activityType = formatterDictData('DIC004', itemData.value.activityType)
		console.log("itemData.value.supportData", itemData.value.supportData)
		itemData.value.activitySupport = formatterDictData('DIC009', itemData.value.activitySupport, 'arr')


		itemData.value.activityRequire = (itemData.value.activityRequire?.split('\n'))?.map((line) => {
			return {
				text: line
			}
		})


		getActivityDetail('init')
		getOrganizationData(itemData.value.teamjsId)
		contactPerson.value = []
		const contactPersonArr = itemData.value.contactPerson
		contactPersonArr.forEach((item) => {
			getContactPersonData(item)
		})

		deadlineDate()

	})



	const addBgColor = (length) => {
		console.log("=============================")
		let colorsList = []
		uni.getStorage({
			key: 'colorsList',
			success(e) {
				console.log("colorsList------", e.data)
				colorsList = e.data
			},

		});
		console.log("length===========", length)
		for (let i = 0; i < length; i++) {
			let bgColor = colorsList[i]
			console.log("bgColor----------", bgColor)
			addBgColorList.value.push(bgColor)
		}
		console.log("addBgColorList.value----------", addBgColorList.value)
	}

	const deadlineDate = () => {
		const now = Date.now();
		const date = new Date(itemData.value.beginTime)
		const end = date.getTime()
		const diff = end - now
		let days, hours, minutes
		console.log("diff----------", diff);
		if (diff < 0) {
			isCanActivity.value = false
		} else {
			isCanActivity.value = true
		}
		console.log("now--------", now);
		console.log("end--------", end);
		console.log("diff--------", diff);
		days = Math.floor(diff / (1000 * 60 * 60 * 24));
		hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
		deadline.value = ` ${days}天${hours}时${minutes}分`;

		console.log("deadline.value--------", deadline.value);

	}

	const getOrganizationData = (teamjsId) => {
		request({
			url: `/api/volunteer/teamjs/${teamjsId}`,
			method: 'GET',
			data: {

			}
		}, e => {
			if (e.success) {
				console.log('e-------------', e)
				organizationData.value = e.data


			} else {
				uni.showToast({
					title: '获取组织信息失败',
					icon: 'none'
				})
			}
		})
	}

	const getContactPersonData = (contactPersonId) => {
		request({
			url: `/api/sys/user/${contactPersonId}`,
			method: 'GET',
			data: {

			}
		}, e => {
			if (e.success) {
				console.log('e-------------', e.data)
				contactPerson.value.push({
					name: e.data.name,
					mobile: e.data.mobile
				})

			} else {
				uni.showToast({
					title: '获取联络人信息失败',
					icon: 'none'
				})
			}
		})
	}


	onMounted(() => {
		uni.getStorage({
			key: 'userData',
			success(e) {
				console.log("userData=============", e)
				userName.value = e.data?.name
			},

		});
	})
</script>



<style lang="scss" scoped>
	.activityDetail-index {
		position: relative;
		box-sizing: border-box;
		background-color: #f5f5f5;
		min-height: 100vh;

		.header {
			background-color: #fff;

			.header_img {
				height: 350rpx;
				border: 1rpx solid #ccc;
				border-radius: 16rpx;


			}

			.header_title {
				font-size: 36rpx;
			}

			.header_mintitle {
				font-size: 24rpx;
				color: #505FFF;

				view {
					background-color: #eceefc;
				}
			}

			.header_time {
				font-size: 26rpx;
				color: #000;

				image {
					width: 32rpx;
					height: 32rpx;
				}

			}


			.header_type {
				text-align: center;
				display: grid;
				grid-template-columns: repeat(2, 1fr);

				.item {
					border-left: 1rpx solid #ccc;
					text-align: center;

					.title {
						color: #505050;
						font-size: 24rpx;
					}

					.text {
						font-size: 28rpx;
					}
				}

				.item:last-child {
					border-right: 1rpx solid #ccc;
				}
			}



			.header_info {
				display: flex;
				box-sizing: border-box;
				background-color: #010209;
				border-radius: 16rpx;
				padding: 15rpx;
				background-image: url('../../static/image/orgination-bg.png');
				background-size: 100% 100%;

				.left_img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 16rpx;
					overflow: hidden;
				}

				.right_person {
					.team_name {
						color: #fff;

					}

					.info {
						font-size: 20rpx;
						color: #fff;
					}
				}

			}
		}

		.volunteerList {
			box-sizing: border-box;
			background-color: #fff;

			.num {
				color: #616161;
				font-size: 24rpx;

				.organizationNum {
					color: #502de5;
					font-size: 26rpx;
					font-weight: bold;
				}
			}

			.person-box {
				display: grid;
				grid-template-columns: repeat(5, 1fr);
				max-height: 400rpx;
				overflow-y: scroll;
				gap: 10rpx;

				.item {
					font-size: 22rpx;


					.item_img {
						font-size: 32rpx;
						color: #fff;
						height: 80rpx;
						width: 80rpx;
						border-radius: 50%;
						overflow: hidden;
					}
				}
			}
		}

		.activeRequirement {
			box-sizing: border-box;
			background-color: #fff;

			.circle {
				display: inline-block;
				width: 12rpx;
				height: 12rpx;
				margin-top: 2rpx;
				background-color: #502DE5;

			}
		}

		.Guarantee {
			box-sizing: border-box;
			background-color: #fff;
		}

		.detail {
			box-sizing: border-box;
			background-color: #fff;

			.info {
				line-height: 50rpx;
				font-size: 28rpx;
				background-color: #dceaff;
				border: 1rpx solid #505fff;
				padding: 20rpx;
			}
		}

		.warning {
			font-size: 26rpx;
			color: #333333;
			padding-bottom: 200rpx;

			.title {
				line-height: 46rpx;
				font-size: 24rpx;
			}
		}

		.Application {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			// height: 100rpx;
			width: 100%;
			box-sizing: border-box;
			padding: 25rpx 40rpx;

			.btn {
				// height: 80rpx;
				border-radius: 80rpx;
				background-image: linear-gradient(#9ba3ff, #253bff);
				text-align: center;
				padding: 10rpx;
				color: #fff;
				// line-height: 80rpx;
			}

			.expire-btn {
				padding: 28rpx 0;
				background-image: linear-gradient(#a3a3a3, #464646);
			}
		}
	}

	.img {
		height: 100%;
		width: 100%;
		// background-color: #ccc;
	}
</style>